#coding:utf-8
import json
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.http.response import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from lovewith.api.qiniu import Qiniu
from lovewith.api.t import WbControlCenter
from lovewith.supplier.views.modules.supplierapi import SupplierApi
from lovewith.utils.mtcache import MtCache
from lovewith.views import site_info
from lovewith.utils.tools import urldecode
from lovewith.share.views.modules.share import ShareApi
from lovewith.share.views.modules.attach import AttachApi
from lovewith.website.views.modules.category import CategoryApi
from lovewith.share.views.modules.attach_tag import AttachTagApi
from lovewith.share.views.modules.attach_color import AttachColorApi
from lovewith.website.views.modules.color import ColorApi


def validate_submit_data(post_data, user):
    share_id = post_data.get('share_id' or None)
    cate_id = post_data.get('cate_id')
    title = post_data.get('title')
    old_images = post_data.getlist('old_images[]')
    new_images = post_data.getlist('new_images[]')
    share_data = None
    cate_data = None

    if share_id:
        share_data = ShareApi.check_data(int(share_id))
    if cate_id:
        cate_data = CategoryApi.check_data(int(cate_id))

    if share_id and not share_data:
        return {'error': True}

    if not cate_data:
        return {'error': True}

    if not title:
        return {'error': True}

    if not len(new_images) and not len(old_images):
        return {'error': True}

    #服务分类非必填
    #if not service_type and user.group_id == 3:
    #    return {'error': True}

    return {'error': False, 'share_data': share_data, 'cate_data': cate_data}


#保存图片信息(tag、color等)
def add_images(images, share_post, cate_data, cover):
    post_cover = None
    #保存图片、标签、颜色
    for i in range(len(images)):
        img_data = urldecode(images[i])
        path = img_data['path'][0]
        tags = img_data['tag'][0]
        colors = img_data['color'][0]
        is_cover = False

        if path == cover:
            is_cover = True

        #保存源文件
        new_path = Qiniu('mt-temp').move(path, 'mt-share')
        new_img = AttachApi.add(new_path, is_cover, share_post)

        if is_cover and not post_cover:
            post_cover = new_path

        #保存颜色
        img_colors = colors.split(',')
        AttachColorApi.add(img_colors, new_img, share_post)
        #保存tag
        img_tags = tags.split(',')
        #增加新的tag
        AttachTagApi.add(img_tags, new_img, cate_data)

    return post_cover


@login_required
def add_share(request):
    if request.method == 'GET':
        image_temp_item = []

        #远程图片
        image_url = request.GET.get('m')
        if image_url:
            image_url = image_url.split('@_@')
            for img in image_url:
                #image_tmp_url = Qiniu('mt-temp').save_remote(img, 'mt-temp')
                #if image_tmp_url:
                image_temp_item.append(img)

        #cate
        cate_data = CategoryApi.get_all()
        #是否是商家
        is_supplier = request.user.group_id == 3 and True or False

        return render_to_response('share/post-image.jinja', {
            'colors': ColorApi.get_all(),
            'cate_data': cate_data,
            'is_supplier': is_supplier,
            'image_temp_item': image_temp_item
        }, context_instance=RequestContext(request, processors=[site_info]))
    else:
        post_data = request.POST
        result = {'error': True}
        #验证表单
        val_result = validate_submit_data(post_data, request.user)

        if not val_result['error']:
            cover = post_data.get('cover')
            title = post_data.get('title')
            content = post_data.get('content')
            new_images = post_data.getlist('new_images[]')
            cate_data = val_result['cate_data']
            scheduled_enable = post_data.get('scheduled_enable') == '1' and True or False

            #添加分享
            new_post = ShareApi.add(title, content, cate_data, request.user, scheduled=scheduled_enable)
            #添加图片
            post_cover = add_images(new_images, new_post, cate_data, cover)

            #用户组为3时添加服务类型
            #if request.user.group_id == 3:
            #    ShareApi.add_service(service_type, new_post, request.user)

            #清空缓存
            for i in range(20):
                MtCache('user_post').delete(user_id=request.user.id, page=i + 1)
                MtCache('cate_share').delete(page=i + 1)

            #同步微博
            content = '我刚刚在婚礼时光分享了 %s http://www.lovewith.me/share/detail/all/%s' % (title, new_post.id)

            if post_cover:
                WbControlCenter(request.user, 'like').send_media(content, '%s!650' % post_cover)
            else:
                WbControlCenter(request.user, 'like').send_text(content)

            result = {'error': False, 'msg': new_post.id}

        return HttpResponse(json.dumps(result))


@login_required
def edit_share(request, share_id):
    if request.method == 'GET':
        share_data = ShareApi.check_data(share_id)
        #分享不存在
        if not share_data:
            return HttpResponseRedirect('/')

        #权限判断
        if share_data.user_id == request.user.id or request.user.is_admin:
            #cate
            cate_data = CategoryApi.get_all()
            #附加数据
            ext_data = []
            img_data = AttachApi.get_by_share(share_data.id)
            for img in img_data.iterator():
                the_data = AttachApi().get_ext_data(img.id)
                ext_data.append(the_data)

            #是否是商家
            is_supplier = request.user.group_id == 3 and True or False

            if share_data.is_video:
                return render_to_response('share/edit-video.jinja', {
                    'colors': ColorApi.get_all(),
                    'cate_data': cate_data,
                    'base_data': share_data,
                    'ext_data': ext_data,
                    'is_supplier': is_supplier,
                }, context_instance=RequestContext(request, processors=[site_info]))
            else:
                return render_to_response('share/edit-image.jinja', {
                    'colors': ColorApi.get_all(),
                    'cate_data': cate_data,
                    'base_data': share_data,
                    'ext_data': ext_data,
                    'is_supplier': is_supplier,
                }, context_instance=RequestContext(request, processors=[site_info]))
        else:
            return HttpResponseRedirect('/')
    else:
        post_data = request.POST

        #验证表单
        val_result = validate_submit_data(post_data, request.user)
        if val_result['error']:
            result = {'error': False}
        else:
            cover = post_data.get('cover')
            title = post_data.get('title')
            content = post_data.get('content')
            old_images = post_data.getlist('old_images[]')
            new_images = post_data.getlist('new_images[]')
            share_data = val_result['share_data']
            cate_data = val_result['cate_data']
            scheduled_enable = post_data.get('scheduled_enable') == '1' and True or False

            #更新基本信息
            share_data.title = title
            share_data.content = content
            share_data.cate = cate_data
            share_data.scheduled_enbale = scheduled_enable

            share_data.save()

            if not share_data.is_video == 1:
                #编辑图片
                old_images_data = {}
                for i in range(len(old_images)):
                    img_data = urldecode(old_images[i])
                    img_id = img_data['imgid'][0]

                    old_images_data[img_id] = {'id': img_id, 'tags': img_data['tag'][0], 'colors': img_data['color'][0]}

                #处理老图片
                image_data = AttachApi.get_by_share(share_data.id)
                for img in image_data:
                    img_data = old_images_data.get(str(img.id) or None)
                    if img_data:
                        image_tags = img_data['tags'].split(',')
                        image_colors = img_data['colors'].split(',')

                        if str(img.id) == cover:
                            img.is_cover = True
                        else:
                            img.is_cover = False
                        img.save()

                        #删除tag
                        AttachTagApi.delete_by_image(img.id)
                        #增加新的tag
                        AttachTagApi.add(image_tags, img, cate_data)

                        #删除color
                        AttachColorApi.delete_by_image(img.id)
                        #增加新的color
                        AttachColorApi.add(image_colors, img, share_data)
                    else:
                        #不存在时，删除原来的图片
                        AttachApi().delete(img.id)

                #保存新图片
                add_images(new_images, share_data, cate_data, cover)
            else:
                #编辑视频
                image_filter_data = AttachApi.get_by_share(share_data.id)
                if image_filter_data.exists():
                    image_data = image_filter_data[0]
                    #更新图片
                    if image_data.path != cover:
                        #删除原图
                        Qiniu('mt-share').delete(image_data.path)
                        #保存新的封面图片
                        new_video_cover = Qiniu('mt-temp').move(cover, 'mt-share')
                        if new_video_cover:
                            image_data.path = new_video_cover
                            image_data.is_cover = 1
                            image_data.save()

                    #处理标签和颜色
                    new_video_data = urldecode(new_images[0])
                    new_video_tags = new_video_data.get('tag')[0].split(',')
                    new_video_colors = new_video_data.get('color')[0].split(',')

                    #删除出原来的标签
                    AttachTagApi.delete_by_image(image_data.id)
                    #批量增加新的tag
                    AttachTagApi.add(new_video_tags, image_data, cate_data)

                    #删除出原来的颜色
                    AttachColorApi.delete_by_image(image_data.id)
                    #批量增加新的颜色
                    AttachColorApi.add(new_video_colors, image_data, share_data)

            #清空缓存
            for i in range(20):
                MtCache('user_post').delete(user_id=request.user.id, page=i + 1)
                MtCache('cate_share').delete(cate_id=share_data.cate_id, page=i + 1)

            result = {'error': False, 'msg': share_data.id}

        return HttpResponse(json.dumps(result))


#添加视频
@login_required
def add_video(request):
    if request.method == 'GET':
        #cate
        cate_data = CategoryApi.get_all()
        #是否是商家
        is_supplier = request.user.group_id == 3 and True or False

        return render_to_response('share/post-video.jinja', {
            'colors': ColorApi.get_all(),
            'cate_data': cate_data,
            'is_supplier': is_supplier
        }, context_instance=RequestContext(request, processors=[site_info]))
    else:
        post_data = request.POST
        result = {'error': True}
        #验证表单
        val_result = validate_submit_data(post_data, request.user)

        if not val_result['error']:
            cover = post_data.get('cover')
            title = post_data.get('title')
            content = post_data.get('content')
            video = post_data.get('video')
            new_images = post_data.getlist('new_images[]')
            cate_data = val_result['cate_data']
            scheduled_enable = post_data.get('scheduled_enable') == '1' and True or False

            #添加分享
            new_post = ShareApi.add(title, content, cate_data, request.user, is_video=True, video=video,
                                    scheduled=scheduled_enable)
            #添加图片
            post_cover = add_images(new_images, new_post, cate_data, cover)

            #清空缓存
            for i in range(20):
                MtCache('user_post').delete(user_id=request.user.id, page=i + 1)
                MtCache('cate_share').delete(page=i + 1)

            #同步微博
            content = '我刚刚在婚礼时光分享了 %s http://www.lovewith.me/share/detail/all/%s' % (title, new_post.id)

            if post_cover:
                WbControlCenter(request.user, 'like').send_media(content, '%s!650' % post_cover)
            else:
                WbControlCenter(request.user, 'like').send_text(content)

            result = {'error': False, 'msg': new_post.id}

        return HttpResponse(json.dumps(result))